import java.io.*;

/** StringOutputStream.
  * Allows to use a PrintWriter and keep a
  * console/history/whatever in a string
  */

class StringOutputStream extends OutputStream
{
  StringBuffer strbuf;
  int L;

  StringOutputStream()
  {
    super();
    L = 1;
    strbuf = new StringBuffer();
  }

  StringOutputStream(int L)
  {
    super();
    this.L = L;
    strbuf = new StringBuffer();
  }

  public synchronized void write(int n)
  {
    char c = (char)n;
    strbuf.append(c);
    if (c == '\n')
      dropExcessLines();
  }

  public synchronized void write(byte[] b, int off, int len)
  {
    // insert in String buffer
    String s = new String(b, off, len);
    strbuf.append(s);
    // if '\n' is present
    if (s.indexOf('\n') != -1)
      dropExcessLines();
  }

  void dropExcessLines()
  {
    String content = strbuf.toString();
    char lastChar = content.charAt(content.length()-1);
    String[] lines = content.split("\n");
    if (lines.length > L)
    {
      int l = 0;
      for (int i=0 ; i < lines.length ; i++)
        l += lines.length;
      strbuf = new StringBuffer(l+L);
      for (int i=lines.length-L ; i < lines.length-1 ; i++)
        strbuf.append(lines[i] + "\n");
      strbuf.append(lines[lines.length-1]);
      if (lastChar == '\n')
        strbuf.append('\n');
    }
  }

  public String toString()
  {
    return strbuf.toString();
  }
}

